package com.nfc.lock.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import java.time.LocalDateTime;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

/**
 * 自动填充公共字段.
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    private static final String CREATE_TIME_FIELD = "createTime";
    private static final String UPDATE_TIME_FIELD = "updateTime";

    @Override
    public void insertFill(MetaObject metaObject) {
        LocalDateTime now = LocalDateTime.now();
        if (metaObject.hasGetter(CREATE_TIME_FIELD) && getFieldValByName(CREATE_TIME_FIELD, metaObject) == null) {
            setFieldValByName(CREATE_TIME_FIELD, now, metaObject);
        }
        if (metaObject.hasGetter(UPDATE_TIME_FIELD) && getFieldValByName(UPDATE_TIME_FIELD, metaObject) == null) {
            setFieldValByName(UPDATE_TIME_FIELD, now, metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasGetter(UPDATE_TIME_FIELD)) {
            setFieldValByName(UPDATE_TIME_FIELD, LocalDateTime.now(), metaObject);
        }
    }
}
